const { app } = require("electron");
const fs = require("fs").promises;
const path = require("path");

const FILE_NAME = "addresses.json";
const filePath = path.join(app.getPath("userData"), FILE_NAME);

let list = [];
// **定义地址模型**
class AddressJsonModel {
    constructor(id, address, signalType, flag) {
        this.id = id; // 唯一主键
        this.address = address;
        this.signalType = signalType;
        this.flag = flag;
    }
}

// **读取本地 JSON（同步）**
async function getAllAddresses() {
    // **三目运算符优化文件读取**
    list = await fs.access(filePath).then(() => fs.readFile(filePath, "utf-8").then(JSON.parse)).catch(() => []);

    // **如果文件为空，则创建默认数据**
    if (list.length === 0) {
        list = Array.from({ length: 6 }, (_, i) => new AddressJsonModel(i + 1, "00000000", "001", "1"));
        await fs.writeFile(filePath, JSON.stringify(list, null, 2));
    }
    return list;
}


// **保存单个地址**
async function addOrUpdateAddress(model) {
    const index = list.findIndex((item) => item.id === model.id);
    if (index !== -1) {
        list[index] = model; // 直接更新数据
    } else {
        list.push(model); // 新增数据
    }
    try {
        await fs.writeFile(filePath, JSON.stringify(list, null, 2));
        return { success: true, error: null };
    } catch (error) {
        return { success: false, error };
    }
}

// **根据 ID 查找地址**
async function findAddressById(id) {
    return await list.find((item) => item.id === id) || null;
}


module.exports = {
    getAllAddresses,
    addOrUpdateAddress,
    findAddressById,
}

